<template>
	<div ref="ThreeDomRef"></div>
</template>

<script setup>
	import * as THREE from 'three';
	import {
		onMounted,
		ref
	} from 'vue';

	const ThreeDomRef = ref(null)
	let camera = null
	
	const initThree = () => {
		// 创建场景、创建相机、创建渲染器
		// 创建场景
		const scene = new THREE.Scene();
		// 创建相机
		camera = new THREE.PerspectiveCamera( 90, window.innerWidth / window.innerHeight, 0.1, 1000 );
		// 渲染器
		const renderer = new THREE.WebGLRenderer();
		renderer.setSize( window.innerWidth, window.innerHeight);
		ThreeDomRef.value.appendChild(renderer.domElement);
		// camera.position.set(0, 0, 0)
		// 创建球体(六面)
		const geometry = new THREE.SphereGeometry( 15, 64, 32 );
		
		// 创建加载器
		const loader = new THREE.TextureLoader();
		
		// 加载图片作为材质
		loader.load(
			// 资源URL
			'/static/tick2.jpg',
		
			// onLoad回调
			function ( texture ) {
				// in this example we create the material when the texture is loaded
				const material = new THREE.MeshBasicMaterial( {
					map: texture,
					side: THREE.DoubleSide
				 });
				 const mesh = new THREE.Mesh(geometry, material)
				 scene.add(mesh)
				 animate()
			},
		
			// 目前暂不支持onProgress的回调
			undefined,
		
			// onError回调
			function ( err ) {
				console.error( 'An error happened.' );
			}
		);
		function animate() {
			renderer.render(scene, camera)
			requestAnimationFrame(animate)
		}
	}
	onMounted(() => {
		initThree()
		ThreeDomRef.value.addEventListener('touchstart', handleStart)
		ThreeDomRef.value.addEventListener('touchmove', handleMove)
	})
	let startX,startY;
	const handleStart = (e) => {
		startX = e.touches[0].clientX;
		startY = e.touches[0].clientY;
	}
	const handleMove = e => {
		const curX = e.touches[0].clientX;
		const curY = e.touches[0].clientY;
		
		const xNum = curX - startX;
		const yNum = curY - startY;
		// 假设手移动了x方向整个屏幕的距离，相机旋转360
		
		const yDeg = xNum*10/window.innerWidth
		const xDeg = yNum * 10 / window.innerHeight
		camera.rotateY(yDeg)
		camera.rotateX(xDeg)
		startX = curX
		startY = curY
	}
</script>

<style>

</style>